package com.du.ichat;

import android.annotation.SuppressLint;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.du.ichat.databinding.ActivityQrcardBinding;
import com.du.ichat.utils.BaseActivity;
import com.du.ichat.utils.CheckSumBuilder;
import com.du.ichat.utils.DialogUtils;
import com.du.ichat.utils.QrCodeUtil;
import com.du.ichat.utils.ScreenUtils;
import com.du.ichat.utils.SpUtils;
import com.du.ichat.utils.UserManager;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.zxing.WriterException;
import com.google.zxing.encoding.EncodingHandler;
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import retrofit2.http.GET;

public class QRCardActivity extends BaseActivity {
    private ActivityQrcardBinding databind;
    private NimUserInfo userInfo;
    private DialogFragment dialog;
    private Bitmap qr1,logo;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        databind = DataBindingUtil.setContentView(this, R.layout.activity_qrcard);
        setSupportActionBar(databind.toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        dialog = DialogUtils.getDialog("正在加载...");
        dialog.show(getSupportFragmentManager() , "dialog");
        databind.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        userInfo = UserManager.getUserinfo(this);
        databind.setUsername(userInfo.getName());
        if (userInfo.getExtensionMap() != null && userInfo.getExtensionMap().containsKey("country")) {
            databind.setAccount(userInfo.getExtensionMap().get("country").toString());
        } else {
            databind.qrcodeTvaccount.setVisibility(View.GONE);
        }

        Glide.with(this).load(userInfo.getGenderEnum().getValue() == 1 ? R.drawable.man : R.drawable.woman).into(databind.qrcodeGenderiv);
        Glide.with(this).load(userInfo.getAvatar()).into(databind.arcardAvatar);

        showQR();

    }

    private void showQR() {
        if(TextUtils.isEmpty(userInfo.getAvatar())){
            logo = BitmapFactory.decodeResource(getResources() , R.mipmap.icon);
            logo = getRoundedBitmap(logo);
            qr1 = QrCodeUtil.createQRCodeWithLogo(userInfo.getAccount(), ScreenUtils.dpToPx(QRCardActivity.this, 260), logo);
            databind.qrcodeQriv.setImageBitmap(qr1);
            DialogUtils.dismiss(dialog , this);
            return;
        }else{
            new AsyncTask<Void,Void,BitmapDrawable>(){
                @Override
                protected BitmapDrawable doInBackground(Void... voids) {
                    BitmapDrawable bd = null;
                    try {
                        bd = (BitmapDrawable) Glide.with(QRCardActivity.this).load(userInfo.getAvatar()).submit().get();
                    } catch (Exception e) {
                        e.printStackTrace();
                        DialogUtils.dismiss(dialog , QRCardActivity.this);
                    }
                    return bd;
                }

                @Override
                protected void onPostExecute(BitmapDrawable bitmapDrawable) {
                    super.onPostExecute(bitmapDrawable);
                    logo = bitmapDrawable.getBitmap();
//                    logo = setImgSize(logo, 0, 0);
                    logo = getRoundedBitmap(logo);
                    Map<String , String> jsonMap = new HashMap<>();
                    jsonMap.put("account" , userInfo.getAccount());
                    jsonMap.put("accountMD5" , CheckSumBuilder.getMD5(userInfo.getAccount()));
                    jsonMap.put("avatar" , CheckSumBuilder.getMD5(userInfo.getAvatar()));
                    JSONObject qrJson = new JSONObject(jsonMap);
                    qr1 = QrCodeUtil.createQRCodeWithLogo(qrJson.toString(), ScreenUtils.dpToPx(QRCardActivity.this, 260), logo);
//                    qr1 = QrCodeUtil.createQRCodeWithLogo(userInfo.getAccount()  + ":" + CheckSumBuilder.getMD5(userInfo.getAccount() + ":" + userInfo.getAvatar()), ScreenUtils.dpToPx(QRCardActivity.this, 260), logo);

                    databind.qrcodeQriv.setImageBitmap(qr1);
                    DialogUtils.dismiss(dialog , QRCardActivity.this);

                }
            }.execute();
        }
    }



    public Bitmap getRoundedBitmap(Bitmap mBitmap) {
        int chang = 15;
        //创建新的位图
        Bitmap bgBitmap = Bitmap.createBitmap(mBitmap.getWidth()+chang, mBitmap.getHeight()+chang , Bitmap.Config.ARGB_8888);
        //把创建的位图作为画板
        Canvas mCanvas = new Canvas(bgBitmap);
        Paint mPaint = new Paint();
        mPaint.setColor(Color.WHITE);
        Rect mRect = new Rect(0, 0, mBitmap.getWidth()+chang, mBitmap.getHeight()+chang);
        Rect mRect1 = new Rect(chang, chang , mBitmap.getWidth(), mBitmap.getHeight());
        RectF mRectF = new RectF(mRect);
        //设置圆角半径为20
        float roundPx = 40;
        mPaint.setAntiAlias(true);
        //先绘制圆角矩形
        mCanvas.drawRoundRect(mRectF, roundPx, roundPx, mPaint);
        //设置图像的叠加模式
        mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        //绘制图像
        mCanvas.drawBitmap(mBitmap, mRect, mRect1, mPaint);
        return bgBitmap;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(qr1 !=null){
            qr1.recycle();
        }
        if(logo !=null){
            logo.recycle();
        }
    }
}
